package com.tianji.learning.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tianji.api.client.user.UserClient;
import com.tianji.api.dto.user.UserDTO;
import com.tianji.common.autoconfigure.mq.RabbitMqHelper;
import com.tianji.common.constants.MqConstants;
import com.tianji.common.domain.dto.PageDTO;
import com.tianji.common.domain.query.PageQuery;
import com.tianji.common.exceptions.BizIllegalException;
import com.tianji.common.exceptions.DbException;
import com.tianji.common.utils.BeanUtils;
import com.tianji.common.utils.CollUtils;
import com.tianji.common.utils.UserContext;
import com.tianji.learning.domain.dto.ReplyDTO;
import com.tianji.learning.domain.po.InteractionReply;
import com.tianji.learning.domain.query.ReplyPageQuery;
import com.tianji.learning.domain.vo.ReplyVO;
import com.tianji.learning.enums.PointsRecordType;
import com.tianji.learning.mapper.InteractionReplyMapper;
import com.tianji.learning.mq.message.PointsMessage;
import com.tianji.learning.service.IInteractionReplyService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 互动问题的回答或评论 服务实现类
 * </p>
 *
 * @author hzy
 * @since 2023-09-09
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class InteractionReplyServiceImpl extends ServiceImpl<InteractionReplyMapper, InteractionReply> implements IInteractionReplyService {

    private final UserClient userClient;
    private final RabbitMqHelper mqHelper;

    /**
     * 新增回答或评论
     *
     * @param dto
     */
    @Override
    public void insertReply(ReplyDTO dto) {

        Boolean isStudent = dto.getIsStudent();
        Long userId = UserContext.getUser();

        if (dto.getAnswerId() == null && dto.getTargetReplyId() == null) {
            throw new DbException("无法显示该数据!!!");
        }
        //新增回答评论
        InteractionReply reply = BeanUtils.copyBean(dto, InteractionReply.class);
        reply.setUserId(userId);
        save(reply);

        //mq发消息 --- 加积分
        //判断是评论还是回答 --- 根据业务需求 , 可以规定是只有回答才加分
        if (dto.getAnswerId() != 0) {
            //评论不加分
            return;
        }
        //没有回复的上级,说明是回答
        mqHelper.send(
                MqConstants.Exchange.LEARNING_EXCHANGE,
                MqConstants.Key.WRITE_REPLY,
                PointsMessage.of(userId, PointsRecordType.QA.getValue())
        );
    }

    /**
     * 分页查询回答和评论列表
     *
     * @param pageQuery
     * @return
     */
    @Override
    public PageDTO<ReplyVO> selectPageQuestions(ReplyPageQuery pageQuery) {
        Integer pageNo = pageQuery.getPageNo();
        Integer pageSize = pageQuery.getPageSize();
        Long questionId = pageQuery.getQuestionId();
        Long answerId = pageQuery.getAnswerId();

        if (questionId == null && answerId == null) {
            throw new BizIllegalException("请求参数异常");
        }

        //查询回答评论
        Page<InteractionReply> page = lambdaQuery()
                .eq(questionId != null, InteractionReply::getQuestionId, questionId)
                .eq(answerId != null, InteractionReply::getAnswerId, answerId)
                .eq(InteractionReply::getHidden, false)
                .page(new Page<>(pageNo, pageSize));
        List<InteractionReply> records = page.getRecords();
        if (CollUtils.isEmpty(records)) {
            return PageDTO.empty(0L, 0L);
        }

        //获取 userId
        Set<Long> userIds = new HashSet<>();
        for (InteractionReply record : records) {
            Long userId = record.getUserId();
            Long targetUserId = record.getTargetUserId();
            userIds.add(userId);
            userIds.add(targetUserId);
        }
        //查询user信息
        List<UserDTO> userDTOS = userClient.queryUserByIds(userIds);
        Map<Long, UserDTO> userMap = userDTOS.stream().collect(Collectors.toMap(UserDTO::getId, u -> u));
        List<ReplyVO> vos = new ArrayList<>();
        for (InteractionReply record : records) {
            ReplyVO replyVO = BeanUtils.copyBean(record, ReplyVO.class);
            //判断是否匿名, 再根据 userId 查询userName , userIcon
            if (!record.getAnonymity()) {
                replyVO.setUserName(userMap.get(record.getUserId()).getName());
                replyVO.setUserIcon(userMap.get(record.getUserId()).getIcon());
            }

            //判断 targetUserId 是否为0
            if (record.getTargetUserId() != 0) {
                replyVO.setTargetUserName(userMap.get(record.getTargetUserId()).getName());
            }
            vos.add(replyVO);
        }
        return PageDTO.of(page, vos);
    }
}
